#include "formula.h"

#include "booleanExpression.h"
#include "expression.h"
#include "substitution.h"

Formula::Formula(Expression * expression, vector<Substitution *> * substitutions)
{
    if(expression == NULL) this->expression = NULL;
    else this->expression = expression->clone();

    if(substitutions != NULL){
        this->substitutions = new vector<Substitution*>();
        for(unsigned int i=0; i<substitutions->size(); i++){
            this->substitutions->push_back(substitutions->at(i)->clone());
        }//for
    }else this->substitutions = NULL;
}

Formula::Formula(const Formula & other)
{
    if(other.expression == NULL) this->expression = NULL;
    else this->expression = other.expression->clone();

    if(other.substitutions != NULL){
        this->substitutions = new vector<Substitution*>();
        for(unsigned int i=0; i<other.substitutions->size(); i++){
            this->substitutions->push_back(other.substitutions->at(i)->clone());
        }//for
    }else this->substitutions = NULL;
}

Formula::~Formula()
{
    delete expression; expression = NULL;

    if(substitutions != NULL){
        for(unsigned int i=0; i<substitutions->size(); i++){
            delete this->substitutions->at(i);
        }//for
        delete substitutions; substitutions= NULL;
    }// if
}

void Formula::setExpression(Expression * expression)
{
    delete this->expression; this->expression = NULL;
    if(expression != NULL) this->expression = expression->clone();
}

void Formula::addSubstitution(const string & attribute, Expression * expression)
{
    if(substitutions == NULL) this->substitutions = new vector<Substitution*>();
    if(expression != NULL) this->substitutions->push_back(new Substitution(attribute,expression));
}

void Formula::setSubstitutions(vector<Substitution*> * substitutions)
{
    if(this->substitutions != NULL){
        for(unsigned int i=0; i<this->substitutions->size(); i++){
            delete this->substitutions->at(i);
        }//for
        delete this->substitutions; this->substitutions= NULL;
    }//if

    if(substitutions != NULL){
        this->substitutions = new vector<Substitution*>();
        for(unsigned int i=0; i<substitutions->size(); i++){
            this->substitutions->push_back(substitutions->at(i)->clone());
        }//for
    }else this->substitutions = NULL;
}

Expression * Formula::getExpression()
{
    return expression;
}

vector<Substitution *> * Formula::getSubstitutions()
{
    return substitutions;
}

Formula * Formula::clone()
{
    return new Formula(*this);
}

string Formula::toString()
{
    string str = "(";
    if(expression != NULL) str = str + expression->toString() + ",";

    str = str + "{";
    if(substitutions!= NULL){
        for(unsigned int i=0; i<substitutions->size(); i++){
            str = str + substitutions->at(i)->toString() + ",";
        }//for
        str.erase(str.length()-1);
    }//if

	str = str + "})";
	return str;
}

